<?php
namespace App\Http\Controllers\Business\Admin\Shop;

use App\Models\AdminUser;
use App\Models\Shop;
use App\Models\User;
use App\Models\City;
use App\Models\SalesmanInfo;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\DB;
use SimpleSoftwareIO\QrCode\Facades\QrCode;
use ZipArchive;
use Exception;
use Log;


class QrcodeManagement{
    //批量生成商家二维码
    public static function batchShopQrcode($cityId, $count=10) {
        $cityName = City::where('id', $cityId)->pluck('name')->first();
        $filename= "../storage/qrcode/".$cityName.date('ymdhis').".zip"; //最终生成的文件名（含路径）
        if(file_exists($filename)){
            unlink($filename);
        }
        //重新生成文件
        $zip = new ZipArchive();
        if($zip->open($filename,ZIPARCHIVE::CREATE)!==TRUE){
            exit('无法打开文件，或者文件创建失败');
        }
        $fileList = [];
        $qrCodeList = [];
        for($i=0;$i<$count; $i++) {
            $qrCodeResult = self::getQrcodeByCityName($cityName);
            if($qrCodeResult['status'] == 'failed') {
                continue;
            }
            $qrCode = $qrCodeResult['data'];
            if(Shop::where('qrcode', $qrCode)->get()->count() > 0) {
                continue;
            }
            if(!in_array($qrCode, $qrCodeList)) {
                array_push($qrCodeList, $qrCode);
            } else {
                continue;
            }
            $file1 = '../storage/qrcode/' . $qrCode . '.png';
            $url1 = env('WEB_URL') . "qrcode/shop/".$qrCode;
            $qrc1 = QrCode::format('png')->size(200)->margin(0)->generate($url1);
            if (!file_exists($file1)) {
                $myFile1 = fopen($file1, 'a+');
            } else {
                $myFile1 = fopen($file1, 'a+');
            }
            fwrite($myFile1, $qrc1);
            fclose($myFile1);
            array_push($fileList, $file1);
        }

        foreach ($fileList as $val) {
            if (file_exists($val)) {
                $zip->addFile($val);
            }
        }
        $zip->close();//关闭
        if (!file_exists($filename)) {
            exit('无法找到文件'); //即使创建，仍有可能失败
        }
        foreach ($fileList as $val) {
           unlink($val);
        }
        return ['status'=>'success', 'data'=>$filename];
    }
    //批量生成个人二维码
    public static function batchUserQrcode($cityId, $count=10) {
        $cityName = City::where('id', $cityId)->pluck('name')->first();
        $filename= "../storage/qrcode/".$cityName."用户".date('ymdhis').".zip"; //最终生成的文件名（含路径）
        if(file_exists($filename)){
            unlink($filename);
        }
        //重新生成文件
        $zip = new ZipArchive();
        if($zip->open($filename,ZIPARCHIVE::CREATE)!==TRUE){
            exit('无法打开文件，或者文件创建失败');
        }
        $fileList = [];
        $qrCodeList = [];
        for($i=0;$i<$count; $i++) {
            $qrCodeResult = self::getQrcodeByCityName($cityName);
            if($qrCodeResult['status'] == 'failed') {
                continue;
            }
            $qrCode = $qrCodeResult['data'];
            if(SalesmanInfo::where('qrcode', $qrCode)->get()->count() > 0) {
                continue;
            }
            if(!in_array($qrCode, $qrCodeList)) {
                array_push($qrCodeList, $qrCode);
            } else {
                continue;
            }
            $file1 = '../storage/qrcode/' . $qrCode . '.png';
            $url1 = env('WEB_URL') . "qrcode/user/".$qrCode;
            $qrc1 = QrCode::format('png')->size(200)->margin(0)->generate($url1);
            if (!file_exists($file1)) {
                $myFile1 = fopen($file1, 'a+');
            } else {
                $myFile1 = fopen($file1, 'a+');
            }
            fwrite($myFile1, $qrc1);
            fclose($myFile1);
            array_push($fileList, $file1);
        }

        foreach ($fileList as $val) {
            if (file_exists($val)) {
                $zip->addFile($val);
            }
        }
        $zip->close();//关闭
        if (!file_exists($filename)) {
            exit('无法找到文件'); //即使创建，仍有可能失败
        }
        foreach ($fileList as $val) {
            unlink($val);
        }
        return ['status'=>'success', 'data'=>$filename];
    }
    //绑定商家二维码
    public static function bindingShopQrcode($cityId, $shopId, $qrCode) {
        if(!$cityId||!$shopId||!$qrCode) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        $shop = Shop::where('id', $shopId)->where('cityid', $cityId)->where('status', 1)->first();
        if(!$shop) {
            return ['status'=>'failed', 'message'=>'获取商家信息失败'];
        }
//        if($shop->qrcode) {
//            return ['status'=>'failed', 'message'=>'该商家已绑定了二维码'];
//        }
        $replaceString = env('WEB_URL') . 'qrcode/shop/';
        $qrCode = str_replace($replaceString, '', $qrCode); //替换一下https://www.fbw-china.com/qrcode/shop/
        if(Shop::where('qrcode', $qrCode)->get()->count()>0) {
            return ['status'=>'failed', 'message'=>'该二维码已绑定了'];
        }
        $shop->qrcode = $qrCode;
        $shop->bindingtime = date("Y-m-d H:i:s");
        $shop->save();
        return ['status'=>'success', 'message'=>'绑定成功'];
    }
    //绑定个人二维码
    public static function bindingUserQrcode($cityId, $userId, $qrCode) {
        if(!$cityId||!$userId||!$qrCode) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        $salesmanInfo = SalesmanInfo::where('salesmanid', $userId)->where('cityid', $cityId)->where('status', 1)->first();
        if(!$salesmanInfo) {
            return ['status'=>'failed', 'message'=>'获取个人信息失败或者帐号被禁用'];
        }
//        if($salesmanInfo->qrcode) {
//            return ['status'=>'failed', 'message'=>'该商家已绑定了二维码'];
//        }
        $replaceString = env('WEB_URL') . 'qrcode/user/';
        $qrCode = str_replace($replaceString, '', $qrCode); //替换一下https://www.fbw-china.com/qrcode/shop/
        if(SalesmanInfo::where('qrcode', $qrCode)->get()->count()>0) {
            return ['status'=>'failed', 'message'=>'该二维码已绑定了'];
        }
        $salesmanInfo->qrcode = $qrCode;
        $salesmanInfo->bindingtime = date("Y-m-d H:i:s");
        $salesmanInfo->save();
        return ['status'=>'success', 'message'=>'绑定成功'];
    }
    //通过城市名称获取二维码
    public static function getQrcodeByCityName($cityName) {
        if(!$cityName) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        $cityNameWordResult = self::makeChineseStringIntoArray($cityName);
        $cityNameString = '';
        //取出城市首字母的两个字
        if($cityNameWordResult['status'] == 'success') {
            $cityNameWordArray = $cityNameWordResult['data'];
            $i = 0;
            foreach($cityNameWordArray as $cityNameWord) {
                if ($i < 2) {
                    $cityNameString .= self::getFirstCharter($cityNameWord);
                    $i++;
                } else {
                    break;
                }
            }
        }
        $len = strlen($cityNameString);
        $qrCode = $cityNameString;
        if($len == 1) {
            $qrCode .= self::getRandChar(4);
        } elseif($len == 2) {
            $qrCode .= self::getRandChar(3);
        } else {
            $qrCode .= self::getRandChar(5);
        }
        trim($qrCode); //去空格
        return ['status'=>'success', 'data'=>$qrCode ];
    }
    //将中文字符串转化成数组
    public static function makeChineseStringIntoArray($str) {
        if(!$str) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        preg_match_all("/./u", $str, $arr);
        if(isset($arr[0])) {
            $data = $arr[0];
        } else {
            return ['status'=>'failed', 'message'=>'转化失败'];
        }
        return ['status'=>'success', 'data'=>$data];
    }
    //获取汉字中的首字母
    public static function getFirstCharter($str){
        if(empty($str)){return '';}
        $fchar=ord($str{0});
        if($fchar>=ord('A')&&$fchar<=ord('z')) return strtoupper($str{0});
        $s1=iconv('UTF-8','gb2312',$str);
        $s2=iconv('gb2312','UTF-8',$s1);
        $s=$s2==$str?$s1:$str;
        $asc=ord($s{0})*256+ord($s{1})-65536;
        if($asc>=-20319&&$asc<=-20284) return 'A';
        if($asc>=-20283&&$asc<=-19776) return 'B';
        if($asc>=-19775&&$asc<=-19219) return 'C';
        if($asc>=-19218&&$asc<=-18711) return 'D';
        if($asc>=-18710&&$asc<=-18527) return 'E';
        if($asc>=-18526&&$asc<=-18240) return 'F';
        if($asc>=-18239&&$asc<=-17923) return 'G';
        if($asc>=-17922&&$asc<=-17418) return 'H';
        if($asc>=-17417&&$asc<=-16475) return 'J';
        if($asc>=-16474&&$asc<=-16213) return 'K';
        if($asc>=-16212&&$asc<=-15641) return 'L';
        if($asc>=-15640&&$asc<=-15166) return 'M';
        if($asc>=-15165&&$asc<=-14923) return 'N';
        if($asc>=-14922&&$asc<=-14915) return 'O';
        if($asc>=-14914&&$asc<=-14631) return 'P';
        if($asc>=-14630&&$asc<=-14150) return 'Q';
        if($asc>=-14149&&$asc<=-14091) return 'R';
        if($asc>=-14090&&$asc<=-13319) return 'S';
        if($asc>=-13318&&$asc<=-12839) return 'T';
        if($asc>=-12838&&$asc<=-12557) return 'W';
        if($asc>=-12556&&$asc<=-11848) return 'X';
        if($asc>=-11847&&$asc<=-11056) return 'Y';
        if($asc>=-11055&&$asc<=-10247) return 'Z';
        return null;
    }
    public static function getRandChar($length){
        $str = '';
        $strPol = "ABDEFGHJLMNQRTVWY23456789abdefghjmnqrtvwy";
        $max = strlen($strPol)-1;
        for($i=0;$i<$length;$i++){
            $str.=$strPol[rand(0,$max)];
        }
        return $str;
    }

}